package com.rainbow.micro.example.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rainbow.common.core.entity.Result;
import com.rainbow.common.core.error.GlobalException;
import com.rainbow.common.core.toolkit.PageHandleUtil;
import com.rainbow.micro.example.dao.RoleMapper;
import com.rainbow.micro.example.dto.req.RoleExcelReq;
import com.rainbow.micro.example.dto.req.RoleQueryReq;
import com.rainbow.micro.example.dto.req.RoleStoreReq;
import com.rainbow.micro.example.dto.resp.RoleExcelResp;
import com.rainbow.micro.example.dto.resp.RoleResp;
import com.rainbow.micro.example.entity.RoleEntity;
import com.rainbow.micro.example.service.RoleService;
import com.rainbow.support.minio.toolkit.MinioUtil;
import com.rainbow.support.mybatis.common.CommonServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
* role服务接口
* 
* @author rainbow
* 邮箱  1335157415@qq.com
* @date 2022-04-30 15:10:42
*/
@Service("roleService")
@RequiredArgsConstructor
@Slf4j
public class RoleServiceImpl extends CommonServiceImpl<RoleMapper, RoleEntity> implements RoleService{

    private final RoleMapper roleMapper;

    private final MinioUtil minioUtil;

    /**
    * 分页查询
    * @param entity 参数
    * @return 查询结果
    */
    @Override
    public PageInfo<RoleResp> page(RoleQueryReq entity){
         PageHelper.startPage(entity.getPageIndex(), entity.getPageSize(), PageHandleUtil.handleSort(entity));
         return new PageInfo<>(roleMapper.select(entity));
    }


    /**
     * 保存数据
     * @param entity 参数
     * @return 保存结果
     */
     @Override
     @Transactional(rollbackFor = Exception.class)
     public boolean save(RoleStoreReq entity) {
        RoleEntity pojo=new RoleEntity();
        BeanUtils.copyProperties(entity,pojo);
        return save(pojo);
     }

    /**
     * 更新数据
     * @param entity 参数
     * @return 更新结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(RoleStoreReq entity) {
        RoleEntity preData= Optional.ofNullable(roleMapper.selectById(entity.getId())).orElseThrow(()->new GlobalException("记录不存在,请检查数据!")) ;
        BeanUtils.copyProperties(entity,preData);
        return updateById(preData);
    }

     /**
     * 逻辑删除
     * @param entity 参数
     * @return 删除结果
     */
     @Override
     public boolean delete(RoleStoreReq entity) {
         return roleMapper.update(null, new LambdaUpdateWrapper<RoleEntity>()
                 .eq(RoleEntity::getId, entity.getId())
                 .set(RoleEntity::getLogicDelete, true)
         ) > 0;
     }

    /**
     * 导入数据
     * @param file 文件
     * @return 导入excel结果
     */
    @Override
    @SneakyThrows
    public Result upload(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setImportFields(new String[]{"主键", "角色id", "角色名称", "角色描述", "状态", "创建时间", "更新时间", "创建人", "更新人", "数据删除标识"});
        List<RoleExcelReq> list = ExcelImportUtil.importExcel(file.getInputStream(), RoleExcelReq.class, params);
        return Result.success(list);
    }

    /**
     * 导出excel
     * @param response 响应结果
     * @param req 请求参数
     * @return 导出结果
     */
    @Override
    @SneakyThrows
    public Result export(HttpServletResponse response, RoleQueryReq req) {
        req.setPageIndex(1);
        req.setPageSize(Integer.MAX_VALUE);
        /*PageInfo<RoleResp> pageInfo = page(req);*/
        /*List<RoleResp> data=pageInfo.getList();*/
        List<RoleExcelResp> list=new ArrayList<>();
       /*  if(ObjectUtils.isNotEmpty(data)){
           for (RoleResp item:data) {
               RoleExcelResp resp = new RoleExcelResp();
               resp.setName(item.getName());
               resp.setDescription(item.getDescription());
               resp.setStatus(item.getStatus());
               list.add(resp);
           }
        }*/
        for (int i = 1; i <100001 ; i++) {
            RoleExcelResp resp = new RoleExcelResp();
            resp.setName("脚盆鸡"+i);
            resp.setDescription("小日本"+i);
            resp.setStatus(i%2);
            list.add(resp);
        }
        ExportParams params = new ExportParams("导出测试", "示例", ExcelType.XSSF);
        params.setTitle(null);
        /*params.setDictHandler(new ExcelDiceAddressListHandlerImpl());*/
        Workbook workbook = ExcelExportUtil.exportExcel(params, RoleExcelResp.class, list);
        String url =minioUtil.upload(convertToStream(workbook),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "example", "示例文档.xlsx",true);
        return Result.success(url);
    }

    /**
     * 上传txt文件
     * @param file 上传文件
     * @return 上传结果
     */
    @Override
    @SneakyThrows
    public Result uploadTxt(MultipartFile file) {
        String str=new String(file.getBytes(), StandardCharsets.UTF_8);
        log.warn("上传文件内容为:{}",str);
        return Result.success(str);
    }

    /**
     * Workbook转换InputStream
     * @param workbook excel参数项
     * @return 转换结果
     */
    @SneakyThrows
    private InputStream convertToStream(Workbook workbook) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        //byte[]转InputStream
        return new ByteArrayInputStream(bos.toByteArray());
    }


}
